package jehc.djshi.sys.init;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import jehc.djshi.common.util.MapUtils;
import jehc.djshi.common.util.PropertisUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 让服务器启动或停止时自动执行代码
 * @author 邓纯杰
 *
 */
@WebListener
@Slf4j
public class InitSetup implements ServletContextListener{
	/**
	 * 停止时执行的方法
	 */
	public void contextDestroyed(ServletContextEvent event) {
		ServletContext sc = event.getServletContext();
	    sc.removeAttribute("syspath");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		log.error(sdf.format(new Date())+"----容器启动出现异常");
	}

	/**
	 * 启动时执行方法
	 */
	public void contextInitialized(ServletContextEvent event) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		ServletContext sc = event.getServletContext();
		try {
	        sc.setAttribute("syspath", getContextPath(sc));
			log.info(""+sdf.format(new Date())+"--->业务平台路径:"+getContextPath(sc));
			log.info(sdf.format(new Date())+"--->进入类加载");
			log.info(sdf.format(new Date())+"--->装载配置文件");
			Map<String, Object> map = PropertisUtil.readProperties(event);
			MapUtils.setKvToServletContext(map, sc);
			map = PropertisUtil.readMessageProperties(event);
			MapUtils.setKvToServletContext(map, sc);
			log.info(sdf.format(new Date())+"--->装载配置结束");

			log.info(sdf.format(new Date())+"--->装载Config配置开始");
			map = PropertisUtil.readConfigProperties(event);
			MapUtils.setKvToServletContext(map, sc);
			log.info(sdf.format(new Date())+"--->装载Config配置结束");
		} catch (Exception e) {
			log.error("启动容器服务出现异常{0}",e.getMessage());
		}
		log.info(sdf.format(new Date())+"--->结束类加载");
	}
	private String getContextPath(ServletContext sc) {
        return sc.getContextPath();
    }
}
